#!/usr/bin/env rc

fn is_rc_script {
  ~ `{head $1 -n1} *rc
}

position=1
available_colors=()
for (color_file in $home/.colors/*) {
  if (is_rc_script $color_file) {
    echo $color_file
    available_colors=($available_colors $color_file)
  }
}

fn show_colors {
  tmpl2linux
  colorgrid
  echo 'Currently viewing: '^`{basename $available_colors($position)}
  echo
}

fn get_next_command {
  echo '[N]ext theme'
  echo '[P]revious theme'
  line=`{head -n1 | awk '{print $1}'} {
    if (~ $line [Nn]*) {
      position=`{echo 1 + $position | bc}
    } else if (~ $line [Pp]*) {
      position=`{echo $position - 1 | bc}
    } else {
      get_next_command
      return
    }

    if (~ $position 0) {
      position=$#available_colors
    } else if (test $position -gt $#available_colors) {
      position=1
    }
  }
}

fn set_colors {
  color=$available_colors($position) {
    rm $home/.current-colors
    ln -s $color $home/.current-colors
    . $color
  }
}

fn run {
  clear
  set_colors
  show_colors
  get_next_command
  run
}

if (~ $#* 1 && test -e $home/.colors/$1) {
  rm $home/.current-colors
  ln -s $home/.colors/$1 $home/.current-colors
  . $home/.current-colors
  tmpl2linux
} else {
  run
}